package tool

import (
	conf "asocrawler/conf"
	"fmt"
	"time"
)

var Worker = NewQiMaiWorker(1024, CallBackFunc)

type CollectFunc interface {
	GetWorkerInfo() (w WorkerInfo)
	Collect(date string) (succ bool, err error)
	Println(v ...interface{})
}
type WorkerInfo struct {
	ChannelName string
}
type QiMaiWorker struct {
	channel    chan CollectFunc
	bufferSize int
	customer   func(CollectFunc)
}

func init() {
	Worker.Start()
}

func NewQiMaiWorker(buffersize int, f func(CollectFunc)) *QiMaiWorker {
	//初始化Worker 并返回
	w := new(QiMaiWorker)
	w.customer = f
	w.bufferSize = buffersize
	w.channel = make(chan CollectFunc, buffersize) //初始化时信道缓存
	return w
}

func (w *QiMaiWorker) Start() {
	//开启工作go程
	go func() {
		for {
			w.customer(<-w.channel)
		}
	}()
}

func (w *QiMaiWorker) Post(any CollectFunc) (bool, int) {
	//这里把信息放入队列
	select {
	case w.channel <- any:
		//返回当前信道缓冲长度,以及总容量
		return true, len(w.channel)
		break
	default:
		return false, 0
		break
	}
	return false, 0
}

func CallBackFunc(this CollectFunc) {
	//间隔一定时间后 执行任务
	timeInterval := GetRandomMinuteNum()
	this.Println(fmt.Sprintf("Worker任务已接收，间隔%s分钟后开始执行", timeInterval))
	time.Sleep(timeInterval * time.Minute)

	var err error

	if conf.Conf.QiMaiCollectMode == "api" {

		if conf.Conf.Debug.Switch {
			// 获取登录后的cookie
			err = SetQiMaiCookieByLogin()
			if err != nil {
				this.Println("获取七麦cookie失败，任务终止,err=", err)
				return
			}
		} else {
			// 获取未登录的cookie
			err = SetQiMaiCookie()
			if err != nil {
				this.Println("获取七麦cookie失败，任务终止,err=", err)
				return
			}
		}

	}

	if conf.Conf.Debug.Switch {
		for _, fDate := range conf.Conf.Debug.DateList {
			this.Println("日期:", fDate, "开始采集数据...")
			succ, err := this.Collect(fDate)
			if succ {
				this.Println("日期:", fDate, "采集数据完成")
			} else {
				if err == nil {
					this.Println("日期:", fDate, "数据未更新")
				} else {
					this.Println("日期:", fDate, "出现错误err:", err)
				}
			}
		}
	} else {
		fDate := time.Now().Format("2006-01-02")
		GetDataOnDate(fDate, this)
	}
}

func GetDataOnDate(date string, this CollectFunc) {
	this.Println("日期:", date, "开始采集的数据...")
	succ, err := this.Collect(date)
	if succ {
		this.Println("日期:", date, "采集数据完成 稍后再次采集...")
	} else {
		if err == nil {
			this.Println("日期:", date, "数据未更新 稍后重新采集...")
		} else {
			channelName := this.GetWorkerInfo().ChannelName
			title := fmt.Sprintf("ASO报警-%s爬虫报错", channelName)
			msg := title + fmt.Sprintf(",错误信息：%s", err.Error())
			SendWarn(title, msg)
			this.Println("日期:", date, "出现错误err:", err, "稍后重新采集...")
		}
	}
}
